
function resetCaptchaForm() {
    $('#captcha-guideline').val('none');
    $('#captcha-form').find('.guideline-control').slideUp();
    
    $('#captcha-label-text').val('');
    $('#captcha-name').val('');
    $('#captcha-id').val('');
    $('#captcha-placeholder').val('');
}

$(function() {
    
    // validation rules
    var rules = {};
    rules['label']                          = set_rules('label', 'label', 'required|maxlength[6]');
    rules['label-text']                     = set_rules('label-text', 'label-text', 'required|maxlength[25]');
    rules['bold-label']                     = set_rules('bold-label', 'bold-label', 'maxlength[25]');
    rules['name']                           = set_rules('name', 'name', 'required|maxlength[50]');
    rules['id']                             = set_rules('id', 'id', 'required|maxlength[50]');
    rules['placeholder']                    = set_rules('placeholder', 'placeholder', 'maxlength[50]');
    rules['icon']                           = set_rules('icon', 'icon', 'required|maxlength[50]');
    rules['change-icon']                    = set_rules('change-icon', 'change-icon', 'maxlength[50]');
    rules['guideline']                      = set_rules('guideline', 'guideline', 'required|maxlength[50]');
    rules['guideline-title']                = set_rules('guideline-title', 'guideline-title', 'required|maxlength[50]');
    rules['guideline-text']                 = set_rules('guideline-text', 'guideline-text', 'required|maxlength[255]');
    rules['horizontal-size']                = set_rules('horizontal-size', 'horizontal-size', 'required|maxlength[25]');
    rules['position']                       = set_rules('position', 'position', 'required|maxlength[25]');

    // fieldset form validation
    $("#captcha-form").validate({
        errorElement: 'small',
        errorClass: 'help-block',
        rules: rules,
        errorPlacement:function(error, element) {
            element.parents('.input-size').append( '<div class="clear-fix"></div>' );
            element.parents('.input-size').append( error);
        },
        highlight: function(label) {
            $(label).closest('.form-group').removeClass('has-error has-success').addClass('has-error');
        },
        success: function(label) {
            label.addClass('valid').closest('.form-group').removeClass('has-error has-success').addClass('has-success');
        }
    });
    
    resetCaptchaForm();
    
    // show/hide label controls
    $('#captcha-label').change(function() {
        if( $(this).val() === 'none' ) {
            $('#captcha-form').find('.label-control').slideUp();
        } else {
            $('#captcha-form').find('.label-control').slideDown();
        }
    });
    
    // auto fill-up captcha name, id and placeholder using label text
    $('#captcha-label-text').change(function() {
        var textLabel = $(this).val().toLowerCase().replace(/ /g,'-');
        ( $('#captcha-name').val() === '' || $('#captcha-name').val() === undefined ) ? $('#captcha-name').val(textLabel) : '';
        ( $('#captcha-id').val() === '' || $('#captcha-id').val() === undefined ) ? $('#captcha-id').val(textLabel) : '';
    });
    
    // auto fill-up captcha id using captcha name
    $('#captcha-name').change(function() {
        if( $('#captcha-label').val() === 'none' ) {
            var textLabel = $(this).val().toLowerCase().replace(/ /g,'-');
            ( $('#captcha-id').val() === '' || $('#captcha-id').val() === undefined ) ? $('#captcha-id').val(textLabel) : '';
        }
    });
    
    // show/hide icon controls
    $('#captcha-icon').change(function() {
        if( $(this).val() === 'none' ) {
            $('#captcha-form').find('.icon-control').slideUp();
        } else {
            $('#captcha-form').find('.icon-control').slideDown();
        }
    });
    
    // show/hide guideline controls
    $('#captcha-guideline').change(function() {
        if( $(this).val() === 'none' ) {
            $('#captcha-form').find('.guideline-control').slideUp();
        } else if(  $(this).val() === 'label' ) {
            $('#captcha-form').find('.guideline-control').slideDown();
            $('#captcha-guideline-title-container').slideUp();
        } else {
            $('#captcha-form').find('.guideline-control').slideDown();
        }
    });

    $('#captcha-save-btn').click(function(event) {
        event.preventDefault();
        $('#captcha-form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });
        
        if( $('#captcha-form').valid()) {

            var values                  = $('#captcha-form').serializeJSON();
            
            // label
            var label                   = ( values['label'] !== undefined && values['label'] !== '' ) ? values['label'] : '';
            var labelPosition           = ( label !== '' || label !== 'none' ) ? ' align-' + label : 'none';
            var labelText               = ( values['label-text'] !== undefined && values['label-text'] !== '' ) ? values['label-text'] : '';
            
            // field data
            var fieldName               = ( values['name'] !== undefined && values['name'] !== '' ) ? values['name'] : '';
            var fieldId                 = ( values['id'] !== undefined && values['id'] !== '' ) ? values['id'] : '';
            var placeholder             = ( values['placeholder'] !== undefined && values['placeholder'] !== '' ) ? ' placeholder="' +values['placeholder']+ '"' : '';
            var initialValue            = ( values['initial-value'] !== undefined && values['initial-value'] !== '' ) ? ' value="' + values['initial-value'] + '"' : '';
            var type                    = ( values['type'] !== undefined && values['type'] !== '' ) ? values['type'] : '';
            
            // captcha
            var length                  = ( values['length'] !== undefined && values['length'] !== '' ) ? values['length'] : '';
            var path                    = ( values['path'] !== undefined && values['path'] !== '' ) ? values['path'] : '';
            var expiration              = ( values['expiration'] !== undefined && values['expiration'] !== '' ) ? values['expiration'] : '';
            var width                   = ( values['width'] !== undefined && values['width'] !== '' ) ? values['width'] : '';
            var height                  = ( values['height'] !== undefined && values['height'] !== '' ) ? values['height'] : '';
            
            // guideline
            var guideline               = ( values['guideline'] !== undefined && values['guideline'] !== '' ) ? values['guideline'] : '';
            var guidelineTitle          = ( values['guideline-title'] !== undefined && values['guideline-title'] !== '' ) ? values['guideline-title'] : '';
            var guidelineText           = ( values['guideline-text'] !== undefined && values['guideline-text'] !== '' ) ? values['guideline-text'] : '';
            
            // size and position
            var horizontalSize          = ( values['horizontal-size'] !== undefined && values['horizontal-size'] !== '' ) ? ' ' + values['horizontal-size'] : '';
            var verticalSize            = ( values['vertical-size'] !== undefined && values['vertical-size'] !== '' )? ' ' + values['vertical-size'] : '';
            var position                = ( values['position'] !== undefined && values['position'] !== '' ) ? ' ' + values['position'] : '';
            
            // validations
            var validations             = values['validations'];
            var required                = $.inArray('required', validations) !== -1 ? ' required="true" ' : ' ';
            var requiredLabel           = ( $.inArray('required', validations) !== -1 && values['label'] !== '' && values['label'] !== 'none') ? ' *' : '';
            
            // icon
            var hasIcon                 = ( values['icon'] !== undefined &&  values['icon'] !== '' && values['icon'] !== 'none' ) ? true : false;
            var icon                    = ( values['icon'] !== undefined && values['icon'] !== '' ) ? values['icon'] : 'none';
            var changeIcon              = ( values['change-icon'] !== undefined && values['change-icon'] !== '' ) ? values['change-icon'] : '<i class="fa fa-camera"></i>';


            var markup = '';
            var list = $('<li class="form-group row"></li>');
            markup += '<button type="button" class="close" aria-hidden="true">&times;</button>\n';
            markup += '<div class="form-group row">\n';
            markup += '<label for="' + fieldId + '-image" class="control-label col-3">\n';
            markup += labelText + ' Image *' + '\n';
            markup += '<br><small>(Click to Refresh)</small>\n';             
            markup += '</label>\n';
            markup += '<div class="control-group col-9">\n';
            markup += '<div class="input-size' + horizontalSize + position + '">\n';
            markup += '<div id="' + fieldId + '-image"></div>\n';
            markup += '</div>\n';
            markup += '</div>\n';                        
            markup += '</div>\n';                        

            markup += '<div class="form-group row">\n';
            markup += '<label for="' +fieldId+ '" class="control-label' +labelPosition+ ' col-3">\n';
            markup += labelText + requiredLabel + '\n';
            markup += '<br><small>' +guidelineText+ '</small>\n';
            markup += '</label>\n';
            markup += '<div class="control-group col-9">\n';
            markup += '<div class="input-size' + horizontalSize + position + '">\n';
            
            if( hasIcon ) {
                markup += '<div class="input-group">';
            }
            if( hasIcon && ( icon === 'left' || icon === 'both' ) ) {
                markup += '<span class="input-group-addon">' +changeIcon+ '</span>';
            }  
            markup += '<input type="text" name="' +fieldName+ '" id="' +fieldId+ '" class="form-control' + verticalSize + '"' + placeholder + initialValue + required + '>\n';
            if( hasIcon && ( icon === 'right' || icon === 'both' ) ) {
                markup += '<span class="input-group-addon">' +changeIcon+ '</span>';
            }
            if( hasIcon ) {
                markup += '</div>';
            }
            markup += '</div>\n';
            markup += '</div>\n';
            
            list.html(markup);
            list.data('controls', values);
            
            $('#form-sortable li:first-child fieldset:first-child ul').prepend(list);
            
            var captchaData = {};
            captchaData['length']       = length;
            captchaData['path']         = path;
            captchaData['expiration']   = expiration;
            captchaData['width']        = width;
            captchaData['height']       = height;
            
            $.post(base_url + 'generator/captcha', captchaData, function(result) {
                $('#' + fieldId + '-image').html(result);
            });

            $('#captcha-modal').modal('hide');

        }
        
        // submit form for validation purposes
        $('#captcha-form').submit();

    });
    
    // generic captcha button
    $('#generic-captcha-btn').click(function() {
        resetCaptchaForm();
        $('#captcha-modal').modal({
            width: '95%'
        });
    });
    
    // captcha button
    $('#captcha-btn').click(function() {
        resetCaptchaForm();
        $('#captcha-modal').modal({
            width: '95%'
        });
    });
    
});

